import {storage} from "../../utils/common";

const auth = {
  state: {
    token: storage().get("token"),
    userInfo: storage().get("userInfo")
  },
  getters: {
    token(state) {
      return state.token
    },
    userInfo(state) {
      return state.userInfo
    }
  },
  mutations: {
    /**
     * 设置token
     * @param state
     * @param token
     */
    setToken: (state, token) => {
      state.token = token
      storage().set("token",token)
    },
    /**
     * 设置用户信息
     * @param state
     * @param userInfo
     */
    setUserInfo: (state, userInfo) => {
      state.userInfo = userInfo
      storage().set('userInfo',userInfo)
    },
    /**
     * 退出登录状态，并清空所有数据
     * @param state
     */
    logout: (state) => {
      state.token = undefined
      state.userInfo = undefined
      storage().clear()
    }
  },
  actions: {
    /**
     * 设置token
     * @param commit
     * @param token
     * @returns {Promise<unknown>}
     */
    setToken({commit}, token) {
      return new Promise(resolve => {
        commit('setToken', token)
        resolve()
      })
    },
    /**
     * 设置用户信息
     * @param commit
     * @param userInfoData
     * @returns {Promise<unknown>}
     */
    login({commit}, userInfoData) {
      return new Promise(resolve => {
        commit('setUserInfo', userInfoData)
        resolve()
      })
    },
    /**
     * 退出登录状态
     * @param commit
     * @returns {Promise<unknown>}
     */
    logout({commit}) {
      return new Promise(resolve => {
        commit('logout')
        resolve(true)
      })
    }
  }
}
export default auth
